package com.wangx1n.boobey.service;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.wangx1n.boobey.entity.pk.PkResult;
import com.wangx1n.boobey.entity.pk.PkRoom;
import com.wangx1n.boobey.entity.pk.Player;
import com.wangx1n.boobey.entity.pk.Problem;
import com.wangx1n.boobey.socket.PkWebsocketServer;
import com.wangx1n.boobey.util.ApiResult;
import com.wangx1n.boobey.util.WordUtil;
import org.springframework.stereotype.Service;

import javax.crypto.interfaces.PBEKey;
import javax.sound.midi.Soundbank;
import javax.websocket.Session;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * @author wangxin
 * @create 2020-06-14 17:51
 */
@Service
public class PkService {
    private static final Integer PROBLEM_NUM = 8;
    //存储用户
    static Map<String,Player> playerMap = new HashMap<String, Player>();
    //存储对战信息
    static List<PkRoom> pkRooms = new LinkedList<PkRoom>();
    Gson gson = new Gson();
    /**
     * 处理客户端发来的消息
     * @param message
     * @param session
     */
    public void clientMessage(String message, Session session){
        JsonObject jsonObject = gson.fromJson(message,JsonObject.class);
        //根据代码对应处理问题
        switch (jsonObject.get("code").getAsInt()){
            //上传用户信息，并且开始匹配
            case 0:
                //获得当前用户对象
                Player player = gson.fromJson(jsonObject.get("userInfo").getAsJsonObject(),Player.class);
                this.addPlayer(player);
                //判断是否匹配到人
                PkRoom pkRoom = this.findPlayer(player);
                if(pkRoom!=null){
                    System.out.println("匹配成功");
                    //添加到对战列表里面
                    pkRooms.add(pkRoom);
                    //向用户发送对战信息
                    this.sendPlayerInfo(pkRoom);
                }
                break;
                //上传得分
            case 1:
                //获得当前用户对象
                Player player1 = gson.fromJson(jsonObject.get("player").getAsJsonObject(),Player.class);
                for(int i=0;i<pkRooms.size();i++){
                    if(pkRooms.get(i).getPlayer1().getOpenid().equals(player1.getOpenid())==true){
                            PkRoom pkRoom1 = pkRooms.get(i);
                            //判断第一个用户是不是自己
                            if(pkRoom1.getPlayer1().getOpenid().equals(player1.getOpenid())==true){
                                //修改list
                                pkRoom1.setPlayer1(player1);
                                pkRooms.set(i,pkRoom1);
                                //判断是否完成，发送完成消息
                                if(jsonObject.get("isOk").getAsBoolean() == true){
                                    this.sendResult(pkRooms.get(i),pkRooms.get(i).getPlayer1().getOpenid());
                                }else {
                                    //发送更新信息
                                    sendScore(pkRooms.get(i));
                                }
                            }
                    }
                    //第二个是自己
                    if(pkRooms.get(i).getPlayer2().getOpenid().equals(player1.getOpenid())==true){
                        PkRoom pkRoom2 = pkRooms.get(i);
                        //修改list
                        pkRoom2.setPlayer2(player1);
                        pkRooms.set(i,pkRoom2);

                        //判断是否完成，发送完成消息
                        if(jsonObject.get("isOk").getAsBoolean() == true){
                            this.sendResult(pkRooms.get(i),pkRooms.get(i).getPlayer2().getOpenid());
                        }else {
                            //发送更新信息
                            sendScore(pkRooms.get(i));
                        }
                    }
                }
                //设置map分数
                for (Player p : playerMap.values()) {
                    //设置分数
                    if(p.getOpenid().equals(player1.getOpenid()) == true){
                       p.setScore(player1.getScore());
                    }
                }
                break;
        }
    }
    /**
     * 发送结果
     * @param pkRoom
     */
    public void sendResult(PkRoom pkRoom,String openid){
        PkResult pkResult = new PkResult();
        if(pkRoom.getPlayer1().getScore()>pkRoom.getPlayer2().getScore()){
                pkResult.setPlayer1(pkRoom.getPlayer1());
                pkResult.setPlayer2(pkRoom.getPlayer2());
        }
        if(pkRoom.getPlayer1().getScore()<pkRoom.getPlayer2().getScore()){
            pkResult.setPlayer1(pkRoom.getPlayer2());
            pkResult.setPlayer2(pkRoom.getPlayer1());
        }
        //如果分数相等
        if(pkRoom.getPlayer1().getScore()==pkRoom.getPlayer2().getScore()){
                if (openid.equals(pkRoom.getPlayer1().getOpenid())==true){
                    pkResult.setPlayer1(pkRoom.getPlayer1());
                    pkResult.setPlayer2(pkRoom.getPlayer2());
                }else{
                    pkResult.setPlayer1(pkRoom.getPlayer2());
                    pkResult.setPlayer2(pkRoom.getPlayer1());
                }
                //加一分
                Player player1 = pkResult.getPlayer1();
                player1.setScore(player1.getScore()+1);
                pkResult.setPlayer1(player1);
        }
        //相差作为得分
        pkResult.setResult(pkResult.getPlayer1().getScore()-pkResult.getPlayer2().getScore());
        try {
            //向用户发送信息
            PkWebsocketServer.sendInfo(gson.toJson(ApiResult.success(pkResult,103)),pkRoom.getPlayer1().getOpenid());
            PkWebsocketServer.sendInfo(gson.toJson(ApiResult.success(pkResult,103)),pkRoom.getPlayer2().getOpenid());
        } catch (IOException e) {
            e.printStackTrace();
        }

//        for (int i = 0;i< pkRooms.size();i++) {
//                playerMap.remove(pkRooms.get(i).getPlayer1().getOpenid());
//                playerMap.remove(pkRooms.get(i).getPlayer2().getOpenid());
//                pkRooms.remove(i);
//            }
//        System.out.println(pkRooms);
        }




    /**
     * 发送得分信息
     * @param pkRoom
     */
    public void sendScore(PkRoom pkRoom){
        try {
            //向用户发送信息
            PkWebsocketServer.sendInfo(gson.toJson(ApiResult.success(pkRoom,102)),pkRoom.getPlayer1().getOpenid());
            PkWebsocketServer.sendInfo(gson.toJson(ApiResult.success(pkRoom,102)),pkRoom.getPlayer2().getOpenid());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 判断用户退出
     * @param openid
     */
    public void exitPlayer(String openid){
        //TODO 还有个bug，用户匹配以后退出，应该删除用户的bug
        for (int i = 0;i< pkRooms.size();i++) {
            if(pkRooms.get(i).getPlayer1().getOpenid().equals(openid)==true){
                //发送结果
                pkRooms.get(i).getPlayer2().setScore(pkRooms.get(i).getPlayer2().getScore()+2);
                this.sendResult(pkRooms.get(i),pkRooms.get(i).getPlayer2().getOpenid());
                System.out.println("玩家1逃跑");
                playerMap.remove(pkRooms.get(i).getPlayer1().getOpenid());
                playerMap.remove(pkRooms.get(i).getPlayer2().getOpenid());
                pkRooms.remove(i);
                break;
            }
            if(pkRooms.get(i).getPlayer2().getOpenid().equals(openid) == true){
                pkRooms.get(i).getPlayer1().setScore(pkRooms.get(i).getPlayer1().getScore()+2);
                //发送结果
                this.sendResult(pkRooms.get(i),pkRooms.get(i).getPlayer1().getOpenid());
                System.out.println("玩家2逃跑");
                //删除用户
               playerMap.remove(pkRooms.get(i).getPlayer1().getOpenid());
                playerMap.remove(pkRooms.get(i).getPlayer2().getOpenid());
                //删除房间
                pkRooms.remove(i);
                break;
            }
        }
        System.out.println(pkRooms);
    }

    /**
     * 发送匹配成功的用户信息
     * @param pkRoom
     */
    public void sendPlayerInfo(PkRoom pkRoom){
        try {
            //向用户发送信息
            PkWebsocketServer.sendInfo(gson.toJson(ApiResult.success(pkRoom,101)),pkRoom.getPlayer1().getOpenid());
            PkWebsocketServer.sendInfo(gson.toJson(ApiResult.success(pkRoom,101)),pkRoom.getPlayer2().getOpenid());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 添加玩家
     */
    public void addPlayer(Player player){
        //判断用户存在
        for (Player p : playerMap.values()) {
            if(p.getOpenid().equals(player.getOpenid()) == true){
                return;
            }
        }
        playerMap.put(player.getOpenid(),player);
    }
    /**
     * 寻找对局
     * @param player
     */
    public PkRoom findPlayer(Player player){
        PkRoom pkRoom = new PkRoom();
        //匹配玩家
        for (Player p : playerMap.values()) {
            if(p.getDictionary() == player.getDictionary()&&(p.isPk() ==false)&&(player.isPk() == false)&&(p.getOpenid()!=player.getOpenid())){
                //设置玩家1
                pkRoom.setPlayer1(playerMap.get(p.getOpenid()));
                //设置玩家1状态
                playerMap.get(p.getOpenid()).setPk(true);
                pkRoom.setPlayer2(playerMap.get(player.getOpenid()));
                playerMap.get(player.getOpenid()).setPk(true);
                //新建题目对象
                List<Problem> problems = new LinkedList<Problem>();
                //生成题目
                for(int i=0;i<PROBLEM_NUM;i++){
                    problems.add(WordUtil.makeProblem(p.getDictionary()));
                }
                //放入问题中
                pkRoom.setProblems(problems);
                return pkRoom;
            }
        }
        return null;
    }
}
